﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using WebNetCorePhoneErp.Model;

namespace WebNetCorePhoneErp.Handler
{
    //IAuthorizationService
    //DefaultAuthorizationService
    //Microsoft.AspNetCore.Mvc.Filters.IAsyncAuthorizationFilter
    //Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter
    // AuthorizeAttribute
    // AuthorizationHandler
    // IAuthorizationHandler
    //AuthorizationHandler
    //IAuthorizationMiddlewareResultHandler
    //AuthorizeFilter
    // AuthorizationHandler<MyRequirement>
    //Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute
    //   DefaultAuthorizationHandlerProvider

    /// <summary>
    /// 检查登录，授权验证
    /// </summary>
    public sealed class LoginFilter : Attribute, IAsyncAuthorizationFilter
    {
        public LoginFilter()
        {
        }

        public LoginFilter(string funId)
        {
            FunId = funId;
        }

        /// <summary>
        /// 方法标识id
        /// </summary>
        private string FunId { get; set; }

        public Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            bool isAjax = IsAjax(context.HttpContext.Request);
            string sessionJson = context.HttpContext.Session.GetString("user");
            if (string.IsNullOrWhiteSpace(sessionJson))
            {
                if (isAjax)
                {
                    //无权访问
                    //context.Result = new UnauthorizedResult();
                    context.Result = new JsonResult(new { Code = 500, Msg = "登录失效，请重新登录" })
                    {
                        StatusCode = StatusCodes.Status401Unauthorized
                    };
                    return Task.CompletedTask;
                }
                //没有登录，去登录
                context.Result = new RedirectResult("/user/LoginView");
                return Task.CompletedTask;
            }
            if (string.IsNullOrWhiteSpace(FunId))
            {
                return Task.CompletedTask;
            }

            ////检查用户权限
            //  var userView = System.Text.Json.JsonSerializer.Deserialize<UserView>(sessionJson);
            bool have = false;//userView.HaveMenuList.Any(x => x.Id == FunId);
            if (have)
            {
                return Task.CompletedTask;
            }         
            if (isAjax)
            {
                //无权访问
                //context.Result = new UnauthorizedResult();
                context.Result = new JsonResult(new { Code = 500, Msg = "你无权访问" })
                {
                    StatusCode = StatusCodes.Status403Forbidden
                };
            }
            else
            {
                //无权访问
                //context.Result = new UnauthorizedResult();
                context.Result = new ContentResult()
                {
                    Content = "你无权访问",
                    StatusCode = StatusCodes.Status403Forbidden
                };
            }
            return Task.CompletedTask;
        }

        /// <summary>
        /// 判断是否为ajax请求
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public static bool IsAjax(HttpRequest req)
        {
            //X-Requested-With: XMLHttpRequest
            bool result = false;
            var xreq = req.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                result = req.Headers["x-requested-with"] == "XMLHttpRequest";
            }
            return result;
        }
    }
}
